<template>
  <div class="tab-title-page goods_add">
    <div class="warn-box" v-if="activeTab != 3">
      <svg-icon style="margin-right:17px" icon-class="warn" :size="20" />
      <p> 商品图片和文字描述不能存在手机号和任何二维码，不得存在微信字样。</p>
    </div>
    <div class="nav_tabs">
      <el-tabs v-model="activeName">
        <el-tab-pane label="商品基础信息" name="base"></el-tab-pane>
        <el-tab-pane>
          <span slot="label" name="meal">套餐设置</span>
        </el-tab-pane>
        <el-tab-pane label="套餐设置1" name="newMeal"></el-tab-pane>
      </el-tabs>
    </div>
    <el-divider class="middle_divider"></el-divider>
    <div class="child_page">
      <template v-if="activeName === 'base'">
        <base-info ref="baseInfo" :draft-id="draftId" :active-tab="activeName"
          @changeTab="activeName = 'meal1'"></base-info>
      </template>
      <template v-if="activeName !== 'base'&&activeName !== 'newMeal'">
        <meal-info ref="mealInfo" :draft-id="draftId" :current-meal="currentMeal" @setTab="setTab"
          @addTab="addTab"></meal-info>
      </template>
      <template v-if="activeName === 'newMeal'">
        <new-meal-info ref="mealInfo" :draft-id="draftId" :current-meal="currentMeal" @setTab="setTab"
          @addTab="addTab"></new-meal-info>
      </template>
    </div>
  </div>
</template>

<script>
import baseInfo from "./child/base";
import mealInfo from "./child/meal";
import newMealInfo from "./child/newMeal";
import { addGoodsData, editGoodsData, deleteGoodsSetmeal, editGoodsSetmeal, addSetmeal } from "@/api/goods";
export default {
  components: { baseInfo, mealInfo,newMealInfo },
  data() {
    return {
      activeName: "base",
      mealTabs: 1,
      isRemove: false,
      count: 0,
      x: 0,
      y: 0,
      timer: null
    }
  },
  props: ['draftId'],
  watch: {
    activeName(val, oldVal) {
      // 切换标签滚动条回到顶部
      document.getElementsByClassName('app-main')[0].scrollTop = 0;
      if (!this.isRemove) {
        const oldIndex = oldVal.substring(4);
        if (this.$refs.mealInfo) {
          this.$refs.mealInfo.saveStorage(oldIndex);
        }
      } else {
        this.isRemove = false;
      }
    },
  },
  computed: {
    currentMeal() {
      return this.activeName.substring(4);
    }
  },
  mounted() {
    if (sessionStorage.getItem('mealInfo')) {
      this.mealTabs = JSON.parse(sessionStorage.getItem('mealInfo')).length;
    }
    // 监听鼠标
    document.onmousemove = (event) => {
      let x1 = event.clientX
      let y1 = event.clientY
      if (this.x !== x1 || this.y !== y1) {
        this.count = 0
      }
      this.x = x1
      this.y = y1
    }
    // 监听键盘
    document.onkeydown = () => {
      this.count = 0
    }
    // 监听Scroll
    document.onscroll = () => {
      this.count = 0
    }
    this.setTimer();
  },
  methods: {
    clearTimer() {
      clearInterval(this.timer);
      this.timer = null;
    },
    setTimer() {
      this.count = 0
      if (!this.timer) {
        this.timer = setInterval(this.cookieTimeout, 1000)
      }
    },
    cookieTimeout() {
      this.count += 1;
      if (this.count === 5 * 60) {
        this.saveToDraft();
      }
      if (this.count > 1000) {
        this.count = 11;
      }
    },
    saveMealItem(submitForm, monthList, dayList, customList) {
      const id = sessionStorage.getItem("goodsId");
      const status = sessionStorage.getItem('goodsStatus');
      if (!submitForm.title) {
        this.$message({
          message: "套餐名字不能为空",
          type: "warning"
        });
        return;
      }
      const params = { goods_id: id, spec: [], ...submitForm, status, operation_type: 1 };
      if (submitForm.lease_set == 1) {
        params.spec = [...monthList];
      } else if (submitForm.lease_set == 2) {
        params.spec = [...dayList];
      } else {
        params.spec = [...customList];
      }
      // 存在套餐id，编辑套餐
      editGoodsSetmeal(params).then(res => { })
    },
    saveMealInfo() {
      const mealInfo = sessionStorage.getItem('mealInfo') ? JSON.parse(sessionStorage.getItem('mealInfo')) : null;
      if (this.$refs.mealInfo && mealInfo) {
        // 当前页为套餐tab
        for (let index in mealInfo) {
          if (index != (this.currentMeal - 1)) {
            const { formData, monthList, dayList, customList } = mealInfo[index];
            this.saveMealItem(formData, monthList, dayList, customList);
          }
        }
        this.$refs.mealInfo.saveToDraft();
      } else if (this.$refs.mealInfo) {
        this.$refs.mealInfo.saveToDraft();
      } else if (mealInfo) {
        // 当前为基础信息tab
        for (let index in mealInfo) {
          const { formData, monthList, dayList, customList } = mealInfo[index];
          this.saveMealItem(formData, monthList, dayList, customList);
        }
      }
    },
    saveBaseInfo(submitForm, goodsParams) {
      const id = sessionStorage.getItem("goodsId");
      const status = sessionStorage.getItem('goodsStatus');
      if (!submitForm.category_id || !submitForm.goods_name) {
        this.$message({
          message: "商品品类和商品名称不能为空",
          type: "warning"
        });
        return;
      }
      const data = { ...submitForm, status, operation_type: 1 };
      data.rent_label = data.rent_label.join(',');
      data.province_id = data.province && data.province[0] ? data.province[0] : "";
      data.show_ity = data.province && data.province[1] ? data.province[1] : "";
      data.carousel_img = data.carousel_img.join(',');
      data.custom = goodsParams.map(item => { return { 'field_title': item.field_title, 'field_val': item.field_type != 3 ? item.field_val : item.field_val.join(',') } });
      delete data.province;
      if (!id) {
        // 没有商品id，新增
        addGoodsData(data).then(res => {
          sessionStorage.setItem('goodsId', res.goods_id);
          this.saveMealInfo();
        })
      } else {
        // 有商品id，编辑
        data.goods_id = id;
        editGoodsData(data).then(res => {
          this.saveMealInfo();
        })
      }
    },
    saveToDraft() {
      // 保存到草稿箱
      if (this.$refs.baseInfo) {
        this.$refs.baseInfo.saveToDraft();
      }
      if (this.$refs.mealInfo) {
        this.$refs.mealInfo.saveToDraft();
      }
      // const baseInfo = sessionStorage.getItem('baseInfo') ? JSON.parse(sessionStorage.getItem('baseInfo')) : null;
      // if (this.$refs.baseInfo) {
      //   const { submitForm, goodsParams } = this.$refs.baseInfo;
      //   this.saveBaseInfo(submitForm, goodsParams);
      // } else if (baseInfo) {
      //   const { formData, goodsParams } = baseInfo;
      //   this.saveBaseInfo(formData, goodsParams)
      // }
    },
    removeTab(index) {
      if (this.mealTabs === 1) {
        this.$message({
          message: "套餐不能为空",
          type: "warning"
        });
        return;
      }
      this.$confirm('您确定要删除该套餐信息吗?', '删除套餐信息', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }).then(() => {
        this.isRemove = true;
        let list = JSON.parse(sessionStorage.getItem('mealInfo'));
        if (list[index] && list[index].formData.setmeal_id) {
          deleteGoodsSetmeal({ goods_id: sessionStorage.getItem("goodsId"), setmeal_id: list[index].formData.setmeal_id }).then(res => {
            list.splice(index, 1);
            this.mealTabs = list.length;
            sessionStorage.setItem('mealInfo', JSON.stringify([...list]));
            if (index === 0) {
              this.activeName = 'base';
            } else {
              this.activeName = 'meal' + index;
            }
          });
        } else {
          list.splice(index, 1);
          this.mealTabs = list.length;
          sessionStorage.setItem('mealInfo', JSON.stringify([...list]));
          if (index === 0) {
            this.activeName = 'base';
          } else {
            this.activeName = 'meal' + index;
          }
        }
      }).catch(() => { });
    },
    setTab(val) {
      this.activeName = val;
    },
    addTab() {
      this.mealTabs += 1;
      this.activeName = 'meal' + this.mealTabs;
    }
  },
  beforeDestroy() {
    this.clearTimer()
  },
  destroyed() {
    sessionStorage.removeItem("baseInfo");
    sessionStorage.removeItem("goodsId");
    sessionStorage.removeItem("mealInfo");
    sessionStorage.removeItem("goodsStatus");
  }
}
</script>

<style lang="scss" scoped></style>